package com.zlf.sb.demo.design.factory;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SceneHandleFactory <A> implements ApplicationContextAware, InitializingBean {
    private final Map<String, List<SceneHandleBase>> statusMap = new HashMap<>();
    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    /**
     * 工厂类初始化后，执行该方法
     * 获取StatusHandleBase所有的实现类
     * @throws Exception
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        Map<String, SceneHandleBase> recommendStrategyMap = applicationContext.getBeansOfType(SceneHandleBase.class);
        if (CollectionUtils.isEmpty(recommendStrategyMap)) {
            return;
        }
        for (SceneHandleBase strategy : recommendStrategyMap.values()) {
            SceneHandleType statusType = strategy.getClass().getAnnotation(SceneHandleType.class);
            if (null == statusType) {
                continue;
            }
            String statusValue = statusType.value();
            if (null == statusValue) {
                continue;
            }
            List<SceneHandleBase> list = statusMap.getOrDefault(statusValue, new ArrayList<>());//同一个注解值，可以对应多个场景实现类
            list.add(strategy);
            statusMap.put(statusValue, list);
        }

    }

    /**
     * 根据条件判断，获取具体场景处理类
     *
     * @param status
     * @return
     */
    public SceneHandleBase getSceneHandle(SceneEnumBase status, A params) {
        String statusType=status.getSceneName();
        //String statusType = String.join(".", status.getClass().getName(), status.getSceneName());
        List<SceneHandleBase> bases = statusMap.get(statusType);
        if (CollectionUtils.isNotEmpty(bases)) {
            for (SceneHandleBase base : bases) {
                if (base.judgeConditions(params)) {//筛选场景实现类
                    return base;
                }
            }
        }
        return null;
    }

}
